package com.zxd.utils;

import org.apache.commons.lang.StringUtils;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;

/**
 * 图片上传工具类
 * Created by 涂奕恒 on 2017/2/15 0015.
 */
public class ImageUtils {

    static final String uploadPath = "/files/upload/";

    public static void delete(String path) {
        try {
            if (StringUtils.isNotBlank(path)) {
                File file = new File(path);
                if (file.exists()) {
                    file.deleteOnExit();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 文件上传
     */
    public static String upload(String webPath, MultipartFile multipartFile) throws Exception {
        String path = "";

        if (null != multipartFile && multipartFile.getOriginalFilename().toLowerCase().trim().length() != 0) {
            String originalFileName = multipartFile.getOriginalFilename().toLowerCase();
            path = uploadPath + originalFileName;

            // 获取项目在磁盘上面的物理路径
            File image = new File(webPath + path);
            File dir = image.getParentFile();
            if (!dir.exists()) {
                boolean result = dir.mkdirs();
                if (result) {
                    System.out.println("创建文件夹成功。。。");
                }
            }

            FileCopyUtils.copy(multipartFile.getBytes(), image);
        }
        return path;
    }

    /**
     * 获取项目在tomcat下的地址
     */
    public static String getWebPath(ServletRequest request) {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpSession session = req.getSession(true);
        String path = session.getServletContext().getRealPath("/").replace(File.separator, "/");
        String[] paths = path.split("/");
        StringBuilder buff = new StringBuilder();
        for (int i = 0; i < paths.length - 1; i++) {
            buff.append(paths[i]).append("/");
        }
        return buff.toString();
    }
}
